<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="单据类型" prop="typeId">
            <el-input v-model="queryParams.typeId" placeholder="请输入单据类型" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="账单名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入账单名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="来往单位" prop="partnerId">
            <el-input v-model="queryParams.partnerId" placeholder="请输入来往单位" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="计划时间" style="width: 308px">
            <el-date-picker
                v-model="dateRangePlanTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item label="执行时间" style="width: 308px">
            <el-date-picker
                v-model="dateRangeExecutionTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['fms:bill:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['fms:bill:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['fms:bill:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['fms:bill:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="billList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="true" />
        <el-table-column label="单据类型" align="center" prop="typeId" >
          <template #default="scope">
            <dict-tag :options="fms_type" :value="scope.row.typeId"/>
          </template>
        </el-table-column>
        <el-table-column label="账单名称" align="center" prop="name" />
        <el-table-column label="记账项目" align="center" prop="classificationItemName" />
        <el-table-column label="来往单位" align="center" prop="partnerName" />
        <el-table-column label="单据编号" align="center" prop="sourceId" />
        <el-table-column label="操作员" align="center" prop="operName" />
        <el-table-column label="应收金额" align="center" prop="costMoney" />
        <el-table-column label="实收金额" align="center" prop="money" />
        <el-table-column label="账户" align="center" prop="accountName" />
        <el-table-column label="计划时间" align="center" prop="planTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行时间" align="center" prop="executionTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.executionTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="fms_bill_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fms:bill:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['fms:bill:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改财务单据对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="billFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据类型" prop="typeId" v-show="false">
          <el-input v-model="form.typeId" placeholder="请输入单据类型" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作员" prop="operId">
              <el-input v-model="form.operId"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单据编号"> 
              <!-- prop="sourceId" -->
              <!-- <el-input v-model="form.sourceId" placeholder="请输入单据编号" /> -->
              <OrderSearch @changeOrder="changeOrder"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来往单位" prop="partnerId">
              <el-input v-model="form.partnerId" placeholder="请输入来往单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账单名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入账单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记账项目" prop="classificationItemId">
              <!-- <el-input v-model="form.classificationItemId" placeholder="请输入记账项目" /> -->
              <el-select v-model="form.classificationItemId" placeholder="请选择记账项目">
                  <el-option
                    v-for="classificationItem in classificationItemList"
                    :key="classificationItem.id"
                    :label="classificationItem.name"
                    :value="classificationItem.id"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应收金额" prop="costMoney">
              <el-input v-model="form.costMoney" placeholder="请输入应收金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实收金额" prop="money">
              <el-input v-model="form.money" placeholder="请输入实收金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划时间" prop="planTime">
              <el-date-picker clearable
                v-model="form.planTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行时间" prop="executionTime">
              <el-date-picker clearable
                v-model="form.executionTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择执行时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="账户" prop="accountId">
              <!-- <el-input v-model="form.accountId" placeholder="请输入账户" /> -->
              <el-select v-model="form.accountId" placeholder="请选择账户">
                  <el-option
                    v-for="account in accountList"
                    :key="account.id"
                    :label="account.name"
                    :value="account.id"
                  ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option
                  v-for="dict in fms_bill_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BillOutside" lang="ts">
import { listAccount } from '@/api/fms/account';
import { AccountVO } from '@/api/fms/account/types';
import { listBill, getBill, delBill, addBill, updateBill } from '@/api/fms/bill';
import { BillVO, BillQuery, BillForm } from '@/api/fms/bill/types';
import { listClassificationItem } from '@/api/fms/classificationItem/index';
import { ClassificationItemVO } from '@/api/fms/classificationItem/types';
import OrderSearch from "./components/search.vue"
import { OrderVO } from '@/api/wms/order/types';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const route = useRoute();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { fms_bill_status } = toRefs<any>(proxy?.useDict('fms_bill_status'));
const { fms_type } = toRefs<any>(proxy?.useDict('fms_type'));

const billList = ref<BillVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangePlanTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeExecutionTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const billFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const fmsBillType = route.query.fmsBillType as string

const initFormData: BillForm = {
  id: undefined,
  typeId: undefined,
  name: undefined,
  classificationItemId: undefined,
  classificationItemName: undefined,
  partnerId: undefined,
  partnerName: undefined,
  sourceId: undefined,
  operId: undefined,
  operName: undefined,
  costMoney: undefined,
  money: undefined,
  accountId: undefined,
  accountName: undefined,
  planTime: undefined,
  executionTime: undefined,
  status: undefined,
  remark: undefined,
}
const data = reactive<PageData<BillForm, BillQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeId: fmsBillType,
    name: undefined,
    partnerId: undefined,
    params: {
      planTime: undefined,
      executionTime: undefined,
    }
  },
  rules: {
    id: [
      { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    typeId: [
      { required: true, message: "单据类型不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "账单名称不能为空", trigger: "blur" }
    ],
    classificationItemId: [
      { required: true, message: "记账项目不能为空", trigger: "blur" }
    ],
    partnerId: [
      { required: true, message: "来往单位不能为空", trigger: "blur" }
    ],
    costMoney: [
      { required: true, message: "应收金额不能为空", trigger: "blur" }
    ],
    money: [
      { required: true, message: "实收金额不能为空", trigger: "blur" }
    ],
    accountId: [
      { required: true, message: "账户不能为空", trigger: "blur" }
    ],
    planTime: [
      { required: true, message: "计划时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态不能为空", trigger: "change" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询财务单据列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangePlanTime.value, 'PlanTime');
  proxy?.addDateRange(queryParams.value, dateRangeExecutionTime.value, 'ExecutionTime');
  const res = await listBill(queryParams.value);
  billList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  billFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangePlanTime.value = ['', ''];
  dateRangeExecutionTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: BillVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.operId = userStore.userId;
  getAccountList();
  getClassificationItemList();
  dialog.visible = true;
  dialog.title = "添加财务单据";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: BillVO) => {
  reset();
  getAccountList();
  getClassificationItemList();
  const _id = row?.id || ids.value[0]
  const res = await getBill(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改财务单据";
}

/** 提交按钮 */
const submitForm = () => {
  billFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBill(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addBill(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: BillVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除财务单据编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delBill(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('fms/bill/export', {
    ...queryParams.value
  }, `bill_${new Date().getTime()}.xlsx`)
}

const changeOrder = (currentOrder?: OrderVO) => {
  form.value.sourceId = currentOrder.value.id;
  form.value.name = currentOrder.value.name;
  form.value.partnerId = currentOrder.value.partnerId;
}

const accountList = ref<AccountVO[]>([]);
/** 查询账户信息列表 */
const getAccountList = async () => {
  const res = await listAccount();
  accountList.value = res.rows;
}

const classificationItemList = ref<ClassificationItemVO[]>([]);
/** 查询记账项目列表 */
const getClassificationItemList = async () => {
  const res = await listClassificationItem();
  classificationItemList.value = res.rows;
}

onMounted(() => {
  getList();
});
</script>
